package com.zy;

import dev.langchain4j.community.model.dashscope.QwenEmbeddingModel;
import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.DocumentParser;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.document.parser.TextDocumentParser;
import dev.langchain4j.data.document.splitter.DocumentByLineSplitter;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.store.embedding.EmbeddingStore;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

/**
 * @program: AI_langchain4j
 * @description:
 * @author: zy
 * @create: 2025-07-05 17:11
 */
@SpringBootApplication
//@EnableDiscoveryClient  // 启用 Nacos 注册发现
public class OpenAiApp_RAG {
    public static void main( String[] args )
    {
        SpringApplication.run(   OpenAiApp_RAG.class, args );
    }

   //启动服务器时，将初始数所厍 rag/a.txt加载到向量库中
   @Bean
   public CommandLineRunner initDataToVectorStore(QwenEmbeddingModel qwenEmbeddingModel,
                                                  EmbeddingStore<TextSegment> embeddingStore) throws Exception {
       URL url = getClass().getClassLoader().getResource("rag/a.txt");
       if (url == null) throw new IllegalStateException("资源 rag/a.txt 未找到");
       Path documentPath = Paths.get(url.toURI());

       return args -> {
           try {
               // 文档加载
               DocumentParser parser = new TextDocumentParser();
               Document doc = FileSystemDocumentLoader.loadDocument(documentPath, parser);
               List<TextSegment> segments = new DocumentByLineSplitter(100, 20).split(doc);  //按行分割

               // 向量化
               List<Embedding> embeddings = qwenEmbeddingModel.embedAll(segments).content();

             //  System.out.println("Embedding 段落数: " + segments.size());
             //  System.out.println("首段文本: " + segments.get(0).text());
               // 入库
               embeddingStore.addAll(embeddings, segments);
               System.out.printf("已初始化向量：%d 条%n", embeddings.size());
           } catch (Exception e) {
               // 打日志，别让 Spring 启动失败
               e.printStackTrace();
           }
       };
   }
}



